const express=require('express');
const mysql=require('mysql');
const uuid=require('uuid/v4');
const crypto=require('crypto');


let server=express();
server.listen(8080);

const db=mysql.createPool({host:'localhost',port:3306,username:'root',password:'',database:'20181225'});

//1接受数据

server.get('/reg',(req,res,next)=>{
	// console.log(req.query);//有query属性

	let {user,pass}=req.query;
	if(!user){
		res.send({code: 1,msg : '用户名不能为空'});
	}else if(!pass){
		res.send({code: 1,msg : '密码不能为空'});
	}else if(!/^\w{6,32}$/.test(user)){
		res.send({code: 1,msg : '用户名不复合规范'});
	}else if(!/^.{6,}$/.test(pass)){
		res.send({code: 1,msg : '密码不复合规范'});
	}else{
		// res.send({code: 0,msg : '注册成功'});
		next()
	}
})
//2校验数据
server.get('/reg',(req,res,next)=>{
	let {user,pass}=req.query;

	db.query(`SELECT * FROM userdata WHERE username='${user}'`,(err,data)=>{
		if(err){
			 res.send({code:1,msg:'数据库有问题'})
		}else if(data.length>0){
			 res.send({code:1,msg:'用户名已存在'});
		}else{
			next();
		}
	});
})


//2.5添加uuid编码
server.get('/reg',(req,res,next)=>{
	let id=uuid().replace(/\-/g,'');
	
	req._uuid=id;//不同的阶段之间共享一个req，所以把id赋值给req.uuid来方便后面的调用

	db.query(`SELECT * FROM userdata WHERE ID ='${id}'`,(err,data)=>{
		if(err){
			res.send({code: 1,msg:'数据库有问题'});
		}else{
			next();
		}
	});
});

//3写入数据
server.get('/reg',(req,res,next)=>{
	let {user,pass}=req.query;
	// console.log(req._uuid);
	let md5=crypto.createHash('md5'); 
	md5.update(pass);
	pass=md5.digest('hex');
	db.query(`INSERT INTO userdata (ID,username,password) VALUES('${req._uuid}','${user}','${pass}')`,(err,data)=>{
		if(err){
			 res.send({code: 1,msg:'数据库有问题'});
		}else{
			 res.send({code: 0,msg : '注册成功'});
			 // console.log(req._uuid);
		}
	});
	// next();
});
